package com.learning.platform.service;

import com.learning.platform.enums.ErrorCode;
import com.learning.platform.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class FileUploadService {
    
    private static final Logger logger = LoggerFactory.getLogger(FileUploadService.class);
    
    @Value("${upload.dir:./uploads}")
    private String uploadDir;
    
    // 允许的图片类型
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"
    );
    
    // 允许的视频类型
    private static final List<String> ALLOWED_VIDEO_TYPES = Arrays.asList(
            "video/mp4", "video/avi", "video/mov", "video/wmv", "video/flv"
    );
    
    // 允许的文档类型
    private static final List<String> ALLOWED_DOCUMENT_TYPES = Arrays.asList(
            "application/pdf", "application/msword", 
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "application/vnd.ms-powerpoint",
            "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    );
    
    /**
     * 上传课程封面
     */
    public String uploadCover(MultipartFile file) {
        validateImageFile(file);
        return uploadFile(file, "covers");
    }
    
    /**
     * 上传课程内容（视频或文档）
     */
    public String uploadLessonContent(MultipartFile file) {
        String contentType = file.getContentType();
        if (!ALLOWED_VIDEO_TYPES.contains(contentType) && !ALLOWED_DOCUMENT_TYPES.contains(contentType)) {
            throw new BusinessException(ErrorCode.UPLOAD_ERROR, "不支持的文件类型");
        }
        
        String subDir = ALLOWED_VIDEO_TYPES.contains(contentType) ? "videos" : "documents";
        return uploadFile(file, subDir);
    }

    /**
     * 上传用户头像
     */
    public String uploadAvatar(MultipartFile file) {
        validateImageFile(file);
        return uploadFile(file, "avatars");
    }
    
    /**
     * 通用文件上传方法
     */
    private String uploadFile(MultipartFile file, String subDir) {
        try {
            // 创建上传目录
            String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            Path uploadPath = Paths.get(uploadDir, subDir, dateDir);
            Files.createDirectories(uploadPath);
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = getFileExtension(originalFilename);
            String filename = UUID.randomUUID().toString() + extension;
            
            // 保存文件
            Path filePath = uploadPath.resolve(filename);
            Files.copy(file.getInputStream(), filePath);
            
            // 返回访问URL
            String relativePath = subDir + "/" + dateDir + "/" + filename;
            String accessUrl = "/uploads/" + relativePath;
            
            logger.info("文件上传成功: originalName={}, savedPath={}, accessUrl={}", 
                    originalFilename, filePath, accessUrl);
            
            return accessUrl;
            
        } catch (IOException e) {
            logger.error("文件上传失败: {}", e.getMessage(), e);
            throw new BusinessException(ErrorCode.UPLOAD_ERROR, "文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证图片文件
     */
    private void validateImageFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.UPLOAD_ERROR, "文件不能为空");
        }
        
        String contentType = file.getContentType();
        if (!ALLOWED_IMAGE_TYPES.contains(contentType)) {
            throw new BusinessException(ErrorCode.UPLOAD_ERROR, "只支持jpg、png、gif、webp格式的图片");
        }
        
        // 检查文件大小（20MB限制）
        if (file.getSize() > 20 * 1024 * 1024) {
            throw new BusinessException(ErrorCode.UPLOAD_ERROR, "图片文件大小不能超过20MB");
        }
    }
    
    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf('.') == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf('.'));
    }
}
